package com.xzy.sms.core.adapter.impl.gx;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xzy.sms.core.adapter.SendSmsAdapter;
import com.xzy.sms.core.entity.SendContext;
import com.xzy.sms.exception.SendSmsException;
import com.xzy.sms.web.domain.entity.ChannelConfig;

/**
 * @desc 广西短信
 * @author wjw
 * @time 2017年11月16日下午3:39:49
 */
public class GxSendSmsAdapter implements SendSmsAdapter {
    
    /** FIXME */
    private static final int MSECOND = 600 * 1000;
    
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    public void sendSms(SendContext smsContext) throws SendSmsException {
        StringBuffer strRespone = new StringBuffer();
        HttpClient client = null;
        try {
            ChannelConfig cc = smsContext.getChannelConfig();
            
            client = new DefaultHttpClient();
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, MSECOND);
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, MSECOND);
            HttpPost post = new HttpPost(cc.getUrl());
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            // 企业总机号
            formparams.add(new BasicNameValuePair("SpCode", cc.getParameter("SpCode")));
            // 短信用户名
            formparams.add(new BasicNameValuePair("LoginName", cc.getAccount()));
            // 短信密码
            formparams.add(new BasicNameValuePair("Password", cc.getPassword()));
            // 内容
            formparams.add(new BasicNameValuePair("MessageContent", smsContext.getContent()));
            // 手机号码
            formparams.add(new BasicNameValuePair("UserNumber", smsContext.getMobile()));
            // 流水号
            formparams.add(new BasicNameValuePair("SerialNumber", String.valueOf(System.currentTimeMillis())));
            // 预约发送时间
            formparams.add(new BasicNameValuePair("ScheduleTime", null));
            
            // String jsonData = URLEncoder.encode(formparams, "UTF-8");
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "GBK");
            // 构造最简单的字符串数据
            // StringEntity reqEntity = new StringEntity(jsonData);
            // 设置类型
            entity.setContentType("application/x-www-form-urlencoded");
            post.setEntity(entity);
            // 执行get请求.
            HttpResponse response = client.execute(post);
            int iStatus = response.getStatusLine().getStatusCode();
            if (iStatus == 200) {
                // 获取响应实体
                org.apache.http.HttpEntity httpEntity = response.getEntity();
                // System.out.println(EntityUtils.toString(httpEntity, "GBK"));
                strRespone.append(EntityUtils.toString(httpEntity, "GBK"));
            } else {
                throw new SendSmsException("短信网关返回意外的HTTP状态码： " + iStatus);
            }
        } catch (IOException e) {
            logger.error("发送短信异常", e);
            throw new SendSmsException("发送短信异 " + e.getMessage(), e);
        }
        String result = strRespone.toString();
        if (result == null || !result.contains("result=0")) {
            throw new SendSmsException("短信网关返回意外的结果： " + result);
        }
    }
    
}
